package com.stox.core.manager;

import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

import com.stox.core.dao.LifeCycleDao;
import com.stox.core.lifecycle.SplashScreen;
import com.stox.core.ui.swing.util.ThrowableReporter;
import com.stox.core.util.Constant;
import com.stox.core.util.PropertiesUtil;
import com.stox.core.util.StringUtil;
import com.stox.design.AfterUiInitializable;
import com.stox.design.ApplicationConfigurer;
import com.stox.design.Initializable;
import com.stox.design.Invokable;
import com.stox.design.Ordered.OrderComparator;
import com.stox.downloader.DownloadManager;
import com.stox.ioc.Container;

public class LifeCycleManager {
	
	private LifeCycleDao lifeCycleDao;
	private DownloadManager downloadManager;
	
	public LifeCycleManager() {
		this.lifeCycleDao = Container.get(LifeCycleDao.class);
		this.downloadManager = Container.get(DownloadManager.class);
	}
	
	public void shutdown(){
		try {
			downloadManager.cancel();
			if(lifeCycleDao != null){
				lifeCycleDao.shutdownDatabase();
			}
		} catch (SQLException e) {
			ThrowableReporter.report(e);
		}
	}
	
	public void startup(){
		if(isFirstRun()){
			setup();
		}
		final SplashScreen splashScreen = new SplashScreen("splash.JPG");
		splashScreen.showSplash();
		initializeComponents();
		splashScreen.dispose();
	}
	
	public <T extends Invokable<?,?>> void invoke(Class<T> clazz){
		List<T> invokables = Container.getImplementations(clazz);
		if(invokables != null && !invokables.isEmpty()){
			Collections.sort(invokables,OrderComparator.instance);
			for(Invokable<?,?> invokable : invokables){
				invokable.invoke(null);
			}
		}
	}
	
	public void runAfterUiInitializables(){
		new Thread(){
			public void run() {
				invoke(AfterUiInitializable.class);
			};
		}.start();
	}
	
	private void initializeComponents(){
		invoke(Initializable.class);
	}
	
	private boolean isFirstRun(){
	/*	
		try {
			String value = WinRegistry.readString (
				    WinRegistry.HKEY_LOCAL_MACHINE,                             //HKEY
				   "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",           //Key
				   "ProductName");
			System.out.println(value);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}   */
		PropertiesUtil propertiesUtil = Container.get(PropertiesUtil.class);
		String installationPath = propertiesUtil.get(Constant.keyInstallationPath);
		return !StringUtil.hasText(installationPath);
	}
	
	private void setup(){
		invoke(ApplicationConfigurer.class);
	}
}
